<?php
//by willson 105328468@qq.com 2014/10/8
class core extends wenyan {
	public $db;
	public $ezr; //分页
	public $tbp;
	public $smarty;
	public $domain;
	public $baidu_ak;
	public $app, $act;
	public $now, $ip;
	public $notify; //消息推送
	public $configs; //配置参数
	public $request;
	public $easemob_org_name, $easemob_app_name, $easemob_client_id, $easemob_client_secret; //环信参数
	public $longitude; //经度, 113.440685
	public $latitude; //纬度, 23.136588
	public $member_id, $member_name, $shop_id, $sign, $is_mini;

	public function __construct() {
		parent::__construct();
		global $db, $ezr, $tbp, $smarty, $domain, $baidu_ak, $act, $app;
		global $notify, $request, $easemob_org_name, $easemob_app_name, $easemob_client_id, $easemob_client_secret;
		if (WX_OPEN && !$this->is_weixin()) $this->weixin_warning();
		$this->db = $db;
		$this->ezr = $ezr;
		$this->tbp = $tbp;
		$this->smarty = $smarty;
		$this->domain = $domain;
		$this->baidu_ak = $baidu_ak;
		$this->app = $app;
		$this->act = $act;
		$this->now = time();
		$this->ip = ip();
		$this->request = $request;
		$this->easemob_org_name = $easemob_org_name;
		$this->easemob_app_name = $easemob_app_name;
		$this->easemob_client_id = $easemob_client_id;
		$this->easemob_client_secret = $easemob_client_secret;
		$this->longitude = isset($_GET['longitude']) ? floatval($_GET['longitude']) : (isset($_SESSION['longitude']) ? floatval($_SESSION['longitude']) : 0);
		$this->latitude = isset($_GET['latitude']) ? floatval($_GET['latitude']) : (isset($_SESSION['latitude']) ? floatval($_SESSION['latitude']) : 0);
		if ($this->longitude) $_SESSION['longitude'] = $this->longitude;
		if ($this->latitude) $_SESSION['latitude'] = $this->latitude;

		//加载配置参数
		$this->configs = array();
		$_config_sql = "SELECT name, memo, content FROM {$this->tbp}config";
		$_configs = $this->db->get_results($_config_sql);
		if ($_configs) {
			foreach ($_configs as $_config) {
				$this->configs[$_config->name] = $_config->content;
				$this->smarty->assign($_config->name,$_config->content);
			}
		}

		//消息推送
		$this->notify = $notify;
		$this->member_id = 0;
		$this->member_name = '';
		$this->shop_id = 0;
		$this->sign = (isset($_GET['sign']) && trim($_GET['sign'])) ? trim($_GET['sign']) : '';
		$this->is_mini = (isset($_REQUEST['is_mini']) && intval($_REQUEST['is_mini']) && $this->is_weixin()) ? intval($_REQUEST['is_mini']) : 0;
		$reseller_id = (isset($_GET['reseller']) && trim($_GET['reseller'])) ? trim($_GET['reseller']) : '';
		if (strlen($reseller_id)) $_SESSION['reseller_id'] = $reseller_id;
		$this->_check_login();
		
		//通过等级积分检测是否需要等级升级处理
		/*
		if ($this->member_id>0) {
			$member_mod = m('member');
			$member_mod->update_grade_from_score($this->member_id);
		}
		*/
		
		$tpl = (isset($_GET['tpl']) && trim($_GET['tpl'])) ? trim($_GET['tpl']) : '';
		if (!$tpl) {
			if (WX_LOGIN && $this->is_weixin() && WX_REGISTER && !$this->is_mini) {
				$this->_check_login();
			} else {
				//需要检查登录状态的方法
				$need_check_login_actions = array(
					'cart' => array(
						'jiesuan', 'order', 'order_complete'
					),
					'order' => array(
						'detail'
					),
					'member' => array(
						'avatar', 'edit_info', 'favorite', 'add_delete_favorite', 'my_invite_user', 'commission_history',
						'withdraw_apply', 'withdraw_history','order','order_detail'
					),
					'recharge' => array(
						'buy', 'history'
					),
					//'index' => array('topic'),
				);
				//检查要登录的模块，如果没有授权，重新授权或重新登录
				foreach($need_check_login_actions as $app_name=>$actions) {
					if ($app == $app_name) {
						foreach ($actions as $action) {
							if ($action == '*' || $act == $action) {
								$this->check_login();
								//微信端防已生成$_SESSION['openid']之后,后退再进入可绕过
								if (WX_LOGIN && $this->is_weixin() && !$this->is_mini) {
									if ($this->weixin_authed()) {
										$openid = $_SESSION['openid'];
										$sql = "SELECT count(*) FROM {$this->tbp}member WHERE openid='{$openid}'";
										$count = $this->db->get_var($sql);
										if (!$count) {
											// header("Location:wap.php?tpl=login.mobile");
											header("Location:wap.php");
											//header("Location:api.php?app=passport&act=login&openid={$openid}");
											exit;
										}
									} else {
										$this->weixin_auth();
									}
								}
							}
						}
					}
				}
			}
		}
		//保存邀请的人
        if (!empty($reseller_id)){
		    //所邀请的人不能是自己
            if ($reseller_id !== $this->member_id){
                //判断所邀请的人是否有上级
                $same = SQL::share('member_invitation')->where("invitation_id='{$this->member_id}'")->find();
                if (empty($same)){
                    //判断所邀请的人是否我的上级
                    $s = SQL::share('member_invitation')->where("invitation_id='{$reseller_id}' AND member_id='{$this->member_id}'")->row();
                    if (empty($s)){
                        SQL::share('member_invitation')->insert(array('member_id'=>$reseller_id, 'invitation_id'=>$this->member_id, 'add_time'=>time()));
                    }
                }
            }
        }
		//日志
		$this->_handle_log();
	}

	//get user id from sign
	public function get_member_from_sign($sign) {
		$sql = "SELECT * FROM {$this->tbp}member WHERE sign='{$sign}' LIMIT 1";
		$member = $this->db->get_row($sql);
		if (!$member) return false;
		$member->total_price = strval($member->money+$member->commission); //总财富
		//写入session
		$_SESSION['member'] = $member;
		$this->member_id = $member->id;
		$this->member_name = $member->name;
		$this->shop_id = $member->shop_id;
		$this->sign = $member->sign;
		return true;
	}

	//通过会员ID获取头像与昵称
	public function get_member_info($member_id) {
		$avatar = '';
		$name = '';
		if ($member_id) {
			//先读取店铺
			$sql = "SELECT avatar, name FROM {$this->tbp}member WHERE id='{$member_id}'";
			$row = $this->db->get_row($sql);
			if ($row) {
				//$row->avatar .= "!logo"; //logo缩略图 by willson 2015/9/6
				$avatar = add_domain($row->avatar);
				$name = $row->name;
			}
		}
		return array('avatar'=>$avatar, 'name'=>$name);
	}

	//动态获取/设置会员属性
	//魔术方法，当设置的属性不存在或者不可访问(private)时就会调用此函数
	public function __set($name, $value) {
		//不设置了
	}
	//魔术方法，当获取的属性不存在或者不可访问(private)时就会调用此函数
	public function __get($name) {
		$perfix = substr($name, 0, 7);
		$property = substr($name, 7);
		if (empty($perfix) || empty($property) || $perfix!='member_' || !isset($_SESSION['member'])) return NULL;
		return isset($_SESSION['member']->$property) ? $_SESSION['member']->$property : NULL;
	}

	//是否登录
	public function _check_login() {
		//已登录
		if (isset($_SESSION['member']) && is_object($_SESSION['member']) && isset($_SESSION['member']->id) && intval($_SESSION['member']->id)>0 && !$this->sign) {
			return $this->get_member_from_sign($_SESSION['member']->sign);
		} else if ($this->sign) {
			return $this->get_member_from_sign($this->sign);
		} else if (WX_LOGIN && $this->is_weixin() && !$this->is_mini) { //以后直接在config修改WX_LOGIN的值就可以控制是否使用微信认证登录
			if (!$this->weixin_authed()) {
				$this->weixin_auth();
				return false;
			}
			return true;
		} else {
			return false;
		}
	}

	//对是否登录函数的封装，如果登录了，则返回true，
	//否则，返回错误信息：-100，APP需检查此返回值，判断是否需要重新登录
	public function check_login(){
		if ($this->_check_login()) {
			return true;
		} else {
			error('请登录', -100);
		}
	}

	//日志
	private function _handle_log() {
		$log = m("log");
		$log->create();
	}

	//消息推送
	public function send_notify($message, $member_id=-1, $goto_target='') {
		$this->send_notify_sms($message, $member_id, '', 0, $goto_target);
	}
	//消息推送与短息，先保存到数据库，再发送
	public function send_notify_sms($message, $member_id=-1, $sms_content='', $template_id=0, $goto_target='') {
		global $sms_api_key;
		$mobile = $udid = '';
		if ($member_id>0) {
			$sql = "SELECT udid, mobile FROM {$this->tbp}member WHERE id='{$member_id}'";
			$member = $this->db->get_row($sql);
			if ($member) {
				$udid = $member->udid;
				$mobile = $member->mobile;
			}
		} else if (isset($_SESSION['member'])) {
			$member_id = $_SESSION['member']->id;
			$udid = $_SESSION['member']->udid;
			$mobile = $_SESSION['member']->mobile;
		}
		//写入消息表
		$message_type = '';
		if (strpos($message, '商品')!==false) {
			$message_type = 'goods';
		} else if (strpos($message, '店铺')!==false) {
			$message_type = 'shop';
		} else if (strpos($message, '订单')!==false) {
			$message_type = 'order';
		} else {
			$message_type = 'html5';
		}
		$this->save_message($message, $member_id, $message_type, $goto_target);
		//发送推送
		if ($udid) $this->notify->send($udid, $message, '', '', array('type'=>'message'));
		//发送短信
		if ((is_array($sms_content) || strlen($sms_content)) && strlen($mobile)) {
			if (strlen($sms_api_key)) $sms_content = $message;
			$sms_id = $this->save_sms($mobile, $sms_content);
			if (send_sms($mobile, $sms_content, $template_id)) $this->save_sms($mobile, $sms_content, $sms_id);
		}
	}
	//操作消息表
	public function save_message($message, $member_id, $message_type='', $goto_target=''){
		if ($member_id>0) {
			$sql = "INSERT INTO {$this->tbp}message (member_id, content, add_time, readed, message_type, goto_target) VALUES
				('{$member_id}', '{$message}', '".time()."', '0', '{$message_type}', '{$goto_target}')";
			$this->db->query($sql);
		} else if ($member_id==0) {
			$sql = "SELECT id FROM {$this->tbp}member WHERE status=1 AND last_time>'".(time()-60*60*24*30)."'"; //一个月内登录过的才发送
			$members = $this->db->get_results($sql);
			if ($members) {
				$sql = "INSERT INTO {$this->tbp}message (member_id, content, add_time, readed, message_type, goto_target) VALUES ";
				foreach ($members as $k=>$g) {
					$sql .= "('{$g->id}', '{$message}', '".time()."', '0', '{$message_type}', '{$goto_target}'),";
				}
				$sql = trim($sql, ',');
				$this->db->query($sql);
			}
		}
	}
	//操作短信表
	public function save_sms($mobile='', $content='', $sms_id=0){
		if ($sms_id>0) {
			$sql = "UPDATE {$this->tbp}sms SET status=1 WHERE id='{$sms_id}'";
			$this->db->query($sql);
		} else {
			$sql = "INSERT INTO {$this->tbp}sms (mobile, content, ip, add_time, status) VALUES
				('{$mobile}', '{$content}', '{$this->ip}', '".time()."', '0')";
			$this->db->query($sql);
			return intval($this->db->insert_id);
		}
	}

	public function is_weixin(){
		if (stripos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')!==false || stripos($_SERVER['HTTP_USER_AGENT'], 'wechatdevtools')!==false) {
			return true;
		} else {
			return false;
		}
	}
	
	//强制使用微信打开提示
	public function weixin_warning() {
		$html = '<title>抱歉，出错了</title><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
			<link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css">
			<div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div>
			<div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>';
		exit($html);
	}

	//强制使用微信登录
	public function weixin_login() {
		if (!$this->weixin_authed(false)) {
			$this->weixin_auth();
		}
	}

	//$shortcut 开启某些方法微信登录
	public function weixin_authed($shortcut=true) {
		if (isset($_SESSION['openid']) && trim($_SESSION['openid']) && isset($_SESSION['weixin']) && isset($_SESSION['member'])) {
			return true;
		} else {
			if ($shortcut) {
				if (in_array($this->act, array('weixin_auth', 'wx_login'))) return true; //白名单
				$shortcut_actions = array(
					/*'home' => array(
						'index'
					),
					'diy' => array(
						'detail'
					),*/
				);
				foreach($shortcut_actions as $app_name=>$actions) {
					if ($this->app == $app_name) {
						foreach ($actions as $act_name) {
							if ($act_name == '*' || $act_name == $this->act) return true;
						}
					}
				}
			}
			return false;
		}
	}

	public function weixin_auth() {
		$appid = WX_APPID;
		$appsecrect = WX_SECRET;
		$userinfo = (isset($_POST['userinfo']) && trim($_POST['userinfo'])) ? stripslashes(trim($_POST['userinfo'])) : '';
		if (!$userinfo) {
			$code = isset($_GET['code']) ? $_GET['code'] : '';
			//先获取code
			if ($code=='') {
				$url = (isset($_GET['url']) && trim($_GET['url'])) ? trim($_GET['url']) : ''; //授权后重定向的回调链接地址(外部网站,请自行urlencode)
				$_SESSION['weixin_url'] = $_SERVER['REQUEST_URI']; //登录后跳转的目标网址
				if (isset($_GET['app']) && isset($_GET['act']) && $_GET['app']=='core' && $_GET['app']=='weixin_auth' && trim($_SERVER['HTTP_REFERER'])) {
					$_SESSION['weixin_url'] = $_SERVER['HTTP_REFERER'];
					if (!trim($_SESSION['weixin_url'])) $_SESSION['weixin_url'] = $_SERVER['REQUEST_URI'];
				}
				if (!isset($_SESSION['weixin_url']) || !trim($_SESSION['weixin_url'])) $_SESSION['weixin_url'] = 'wap.php';
				$redirect_url = $url ? $url : urlencode(https().$_SERVER['SERVER_NAME']."/api.php?app=core&act=weixin_auth");
				$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_url}".
					"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
				header("Location:{$url}");
				exit;
			}
			//用户授权
			$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecrect}&code={$code}&grant_type=authorization_code";
			$html = file_get_contents($url);
			$json = json_decode($html);
			//print_r($json);
			if (isset($json->errcode) && intval($json->errcode)!=0) error($json->errmsg);
			$openid = $json->openid;
			$_SESSION['openid'] = $openid;
			//获取用户信息
			$url = "https://api.weixin.qq.com/sns/userinfo?access_token={$json->access_token}&openid={$json->openid}&lang=zh_CN";
			$html = file_get_contents($url);
			$json = json_decode($html);
		} else {
			$json = json_decode($userinfo);
			$openid = $json->openid;
			$_SESSION['openid'] = $openid;
		}
		$nickname = isset($json->nickname) ? $json->nickname : $json->nickName;
		//$nickName = preg_replace('/\xEE[\x80-\xBF][\x80-\xBF]|\xEF[\x81-\x83][\x80-\xBF]/', '', $json->nickname);
		//$nickname = addslashes($json->nickname);
		$json->nickname = $nickname;
		$sex = isset($json->sex) ? $json->sex : $json->gender;
		if (is_numeric($sex)) $sex = intval($sex)==1 ? '男' : '女';
		$json->sex = $sex;
		$headimgurl = isset($json->headimgurl) ? $json->headimgurl : $json->avatarUrl;
		$json->headimgurl = $headimgurl;
		$_SESSION['weixin'] = $json;
		
		//$url = 'wap.php?tpl=login.mobile';
		$url = (isset($_SESSION['weixin_url']) && trim($_SESSION['weixin_url'])) ? trim($_SESSION['weixin_url']) : 'wap.php';
		
		$sql = "SELECT * FROM {$this->tbp}member WHERE openid='{$openid}' OR mini_openid='{$openid}' OR (nick_name='{$nickname}' AND sex='{$sex}')";
		$member = $this->db->get_row($sql);
		if (!$member) {
			if (WX_REGISTER || $userinfo) {
				$wx_openid = $mini_openid = $openid;
				if ($userinfo) {
					$wx_openid = '';
				} else {
					$mini_openid = '';
				}
				$salt = generate_salt();
				$password = random_str(8);
				$crypt_password = crypt_password($password, $salt);
				$sign = generate_sign();
				$sql = "INSERT INTO {$this->tbp}member (password, origin_password, salt, real_name, nick_name, sex, province, city,
					avatar, openid, mini_openid, reg_time, reg_ip, sign, status) VALUES 
					('{$crypt_password}', '{$password}', '{$salt}', '{$json->nickname}', '{$json->nickname}', '{$json->sex}', '{$json->province}', '{$json->city}',
					'{$json->headimgurl}', '{$wx_openid}', '{$mini_openid}', '".time()."', '{$this->ip}', '{$sign}', '1')";
				$this->db->query($sql);
				$sql = "SELECT * FROM {$this->tbp}member WHERE openid='{$openid}'";
				$member = $this->db->get_row($sql);
				$member->total_price = strval($member->money+$member->commission); //总财富
				$_SESSION['member'] = $member;
				$this->_check_login();
				if (!$userinfo) header("location:{$url}");
			} else {
				$_POST = json_decode($html, true);
				$_POST['source'] = 'wechat';
				$_POST['hash'] = $openid;
				$_SESSION['member_temp'] = $_POST;
				header("Location:wap.php?tpl=login.mobile");
				//不绑定手机，直接去登录页面
				//header("Location:api.php?app=passport&act=login&openid={$openid}"); //增加openid参数是为了指定当前不是主动登录
			}
		} else {
			$sign = generate_sign();
			$member->total_price = strval($member->money+$member->commission); //总财富
			$member->sign = $sign;
			$set = '';
			if ($userinfo) {
				$member->mini_openid = $openid;
				$set = ", mini_openid='{$openid}'";
			} else {
				$member->openid = $openid;
				$set = ", openid='{$openid}'";
			}
			$sql = "UPDATE {$this->tbp}member SET sign='{$sign}' {$set} WHERE id='{$member->id}'";
			$this->db->query($sql);
			$_SESSION['member'] = $member;
			$this->_check_login();
			if (strlen($member->mobile)) {
				$url = (isset($_SESSION['weixin_url']) && trim($_SESSION['weixin_url'])) ? trim($_SESSION['weixin_url']) : 'wap.php';
			}
			if (!$userinfo) header("Location:{$url}");
		}
		if ($userinfo) success($member);
		exit;
	}
	
	//设置分页的参数
	public function setpages($data=array()) {
		$BRSR = (isset($_GET['BRSR']) && trim($_GET['BRSR'])) ? trim($_GET['BRSR']) : '';
		$this->smarty->assign('BRSR', $BRSR);
		$this->ezr->set_qs_val('app', $this->app);
		$this->ezr->set_qs_val('act', $this->act);
		foreach ($data as $key=>$value) {
			$this->ezr->set_qs_val($key, $value);
			$this->smarty->assign($key, $value);
		}
	}
}
